package com.ygqh.baby.observer;

import com.ygqh.baby.ao.OrderStatus;
import com.ygqh.baby.model.ProductBookRecordModel;
import com.ygqh.baby.observer.Observable.OrderPaySuccessObservable;
import com.ygqh.baby.po.YgOrder;
import com.ygqh.baby.po.YgPrepayBookRecord;
import com.ygqh.baby.po.YgUser;
import com.ygqh.baby.service.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

/**
 * 定金膨胀支付/取消
 * @Auther: sunshuo
 * @Date: 2018/7/30 11:30
 * @Description:
 */
@Component
public class ProductBookRecordPaidOrCancelObserver implements Observer {

	private Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private YgPrepayBookRecordService ygPrepayBookRecordService;
	@Autowired
	private YgOrderLogService ygOrderLogService;
	@Autowired
	private WxMpMessageService wxMpMessageService;
	@Autowired
	private YgOrderService ygOrderService;
	@Autowired
	private YgUserService ygUserService;
	@Value("${promotion.link}")
	protected String promotionLink;

	@Override
	public void update(Observable o, Object arg) {
		OrderPayModel model = arg != null ? (OrderPayModel) arg : null;
		if (model == null || model.getOrderId() == null) {
			logger.error(o.getClass().getName() + ": orderId为空");
		}
		if (o instanceof OrderPaySuccessObservable) {
			YgPrepayBookRecord record = ygPrepayBookRecordService.findByRecordCode(model.getOrderId());
			if (record != null) {
				doPaidSuccessByRecordCode(record, model);
			} else {
				List<ProductBookRecordModel> recordList = ygPrepayBookRecordService.findByOrderId(model.getOrderId(), YgPrepayBookRecord.RecordStatus.WaitingPayFinal);
				if (CollectionUtils.isNotEmpty(recordList)) {
					doPaidSuccessByOrderId(recordList, model);
				}
			}
		}
	}

	/**
	 * 活动订单尾款支付成功
	 * @param recordList
	 * @param model
	 */
	private void doPaidSuccessByOrderId(List<ProductBookRecordModel> recordList, OrderPayModel model) {
		YgOrder mainOrder = ygOrderService.findOrderDetailByOrderId(model.getOrderId());
		if (mainOrder == null || model.getTotalPrice().compareTo(mainOrder.getTotalPrice()) != 0) {
			return;
		}
		Date now = new Date();
		BigDecimal bookPrice = BigDecimal.ZERO;
		for (ProductBookRecordModel record : recordList) {
			bookPrice = bookPrice.add(record.getBookPrice());
			YgPrepayBookRecord update = new YgPrepayBookRecord();
			update.setId(record.getId());
			update.setRecordStatus(YgPrepayBookRecord.RecordStatus.Complete);
			update.setTailPaidTime(now);
			ygPrepayBookRecordService.update(update);
			/**
			 * 记录订单日志
			 */
			ygOrderLogService.addOrderLog(record.getRecordCode(), OrderStatus.WaitingSend, "支付回调", "活动订单尾款支付成功;");
		}
		/*
		 * 主订单支付成功，修改主单订单金额和应收支付金额；
		 * 最终订单支付金额=定金支付金额+订单支付金额
		 * */
		YgOrder updateOrder = new YgOrder();
		updateOrder.setId(mainOrder.getId());
		BigDecimal totalPrice = mainOrder.getTotalPrice().add(bookPrice);
		updateOrder.setTotalPrice(totalPrice);
		updateOrder.setPaidPrice(totalPrice);
		ygOrderService.update(updateOrder);
	}

	/**
	 * 活动订单定金支付成功
	 * @param record
	 * @param model
	 */
	private void doPaidSuccessByRecordCode(YgPrepayBookRecord record, OrderPayModel model) {
		if (!record.getRecordStatus().equals(YgPrepayBookRecord.RecordStatus.WaitingPayDepost)) {
			ygOrderLogService.addOrderLog(record.getRecordCode(), OrderStatus.WaitingSend, "支付回调", "该活动订单定金存在重复支付;支付流水号："
					+ model.getPaymentCode());
			return;
		}
		if (model.getTotalPrice().compareTo(record.getBookPrice()) != 0) {
			ygOrderLogService.addOrderLog(record.getRecordCode(), OrderStatus.WaitingSend, "支付回调", "该活动订单定金支付金额与实际金额不符;bookPrice="
					+ record.getBookPrice() + "paidPrice=" + model.getTotalPrice());
			return;
		}
		/**
		 * 修改活动订单记录状态
		 */
		YgPrepayBookRecord updateRecord = new YgPrepayBookRecord();
		updateRecord.setId(record.getId());
		updateRecord.setRecordStatus(YgPrepayBookRecord.RecordStatus.WaitingPayFinal);
		updateRecord.setBookPaidTime(new Date());
		ygPrepayBookRecordService.update(updateRecord);
		/**
		 * 发送支付消息
		 */
		String url = promotionLink + "/user/depositdetail.html?recordCode=" + record.getRecordCode();
		YgUser user = ygUserService.findById(record.getUserId());
		wxMpMessageService.sendOrderPaySuccessMsg(null, record.getRecordCode(), user.getOpenId(), model.getTotalPrice(),
				record.getProductName(), 1, url);
		/**
		 * 记录订单日志
		 */
		ygOrderLogService.addOrderLog(record.getRecordCode(), OrderStatus.WaitingSend, "支付回调", "活动订单定金支付成功;");
	}

}
